package reply

import (
	"context"
	"fmt"

	"mall/service/backend/api/internal/lib/memberrank"
	"mall/service/backend/api/internal/logic/forum/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/forum/rpc/forumclient"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetPostByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPostByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostByIdLogic {
	return &GetPostByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPostByIdLogic) GetPostById(req *types.IDReq) (resp *types.ForumPostInfoResp, err error) {
	if req.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.ForumRpc.BackendGetReplyById(l.ctx, &forumclient.IDReq{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}

	var media []*types.MediaInfo
	if len(res.Media) > 0 {
		for _, v := range res.Media {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			media = append(media, &types.MediaInfo{
				Uid:       v.Uid,
				Id:        v.Id,
				Url:       pointy.GetPointer(url),
				Thumbnail: v.Thumbnail,
				AltText:   v.AltText,
				MetaData:  v.Meta,
				Order:     v.Order,
			})
		}
	}

	var meta []*types.MetaInfo
	if len(res.Meta) > 0 {
		for _, v := range res.Meta {
			meta = append(meta, &types.MetaInfo{
				Id:    v.Id,
				Key:   v.Key,
				Value: v.Value,
			})
		}
	}

	memberRankMap := l.getMemberRankMap()

	var topic *types.ForumTopicInfo
	if res.Topic != nil {
		v := res.Topic
		var author *types.ForumAuthorInfo
		var levelName *string
		var levelUrl *string
		if v.Author != nil && memberRankMap != nil && v.Author.Level != nil && *v.Author.Level > 0 {
			if memberRank, ok := memberRankMap[*v.Author.Level]; ok {
				levelName = memberRank.Name
				levelUrl = memberRank.PicUrl
			}
		}
		if v.Author != nil && v.Author.Name != nil {
			var anonymous *bool
			if v.Author.Anonymous != nil {
				anonymous = pointy.GetPointer(*v.Author.Anonymous > 0)
			}
			author = &types.ForumAuthorInfo{
				Id:        v.Author.Id,
				Name:      v.Author.Name,
				Avatar:    v.Author.Avatar,
				Ip:        v.Author.Ip,
				Level:     v.Author.Level,
				Anonymous: anonymous,
				LevelName: levelName,
				LevelUrl:  levelUrl,
			}
		}
		var statusText *string
		if v.Status != nil {
			statusText = pointy.GetPointer(util.GetStatusText(int32(*v.Status)))
		}
		topic = &types.ForumTopicInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        v.Id,
				CreatedAt: v.CreatedAt,
				UpdatedAt: v.UpdatedAt,
			},
			ForumId:      v.ForumId,
			AuthorId:     v.AuthorId,
			Title:        v.Title,
			Slug:         v.Slug,
			Status:       v.Status,
			StatusText:   statusText,
			Sticky:       v.Sticky,
			ReplyCount:   v.PostCount,
			CommentCount: v.CommentCount,
			Author:       author,
		}
	}

	var author *types.ForumAuthorInfo
	var levelName *string
	var levelUrl *string
	if memberRankMap != nil && res.Author != nil && res.Author.Level != nil && *res.Author.Level > 0 {
		if memberRank, ok := memberRankMap[*res.Author.Level]; ok {
			levelName = memberRank.Name
			levelUrl = memberRank.PicUrl
		}
	}
	if res.Author != nil && res.Author.Name != nil {
		var anonymous *bool
		if res.Author.Anonymous != nil {
			anonymous = pointy.GetPointer(*res.Author.Anonymous > 0)
		}
		author = &types.ForumAuthorInfo{
			Id:        res.Author.Id,
			Name:      res.Author.Name,
			Avatar:    res.Author.Avatar,
			Ip:        res.Author.Ip,
			Level:     res.Author.Level,
			Anonymous: anonymous,
			LevelName: levelName,
			LevelUrl:  levelUrl,
		}
	}

	var statusText *string
	if res.Status != nil {
		statusText = pointy.GetPointer(util.GetStatusText(int32(*res.Status)))
	}

	option := util.GetOptionByStatusAndType(res.Status, res.Sticky, res.ForumId)

	return &types.ForumPostInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.ForumPostInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         res.Id,
				CreatedAt:  res.CreatedAt,
				UpdatedAt:  res.UpdatedAt,
				DeletedAt:  res.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			ForumId:        res.ForumId,
			ContentHtml:    res.ContentHtml,
			AuthorId:       res.AuthorId,
			TopicId:        res.TopicId,
			Media:          media,
			Meta:           meta,
			Status:         res.Status,
			StatusText:     statusText,
			Sticky:         res.Sticky,
			CommentStatus:  res.CommentStatus,
			CommentCount:   res.CommentCount,
			PhotoCount:     res.PhotoCount,
			Author:         author,
			Topic:          topic,
			CanStick:       option.CanStick,
			CanUnstick:     option.CanUnstick,
			CanForceDelete: option.CanForceDelete,
		},
	}, nil
}

func (l *GetPostByIdLogic) getMemberRankMap() map[uint32]*types.MemberRankInfo {
	memberRank := memberrank.NewMemberRank(l.ctx, l.svcCtx)
	memberRankList, err := memberRank.List()
	if err != nil {
		logrus.Info(fmt.Sprintf("GetPostById getMemberRankMap err: %+v", err))
		return nil
	}

	if len(memberRankList) > 0 {
		resp := make(map[uint32]*types.MemberRankInfo)
		for _, v := range memberRankList {
			if v.Id != nil && *v.Id > 0 {
				resp[uint32(*v.Id)] = v
			}
		}

		return resp
	}

	return nil
}
